<?php

class UserModel
{
    private $userInfoKeyPrefix  =   'UI/';
    private $abilityKeyPrefix   =   'EX/';
    private static $userInfo    =   array();
    private $slaveKey           =   '/slave';
    private $userConKeyPrefix   =   'UCN/';
    private $deviceInfoPrefix   =   'DI/';

    public function getUserInfo($uid, $allInfo = FALSE)/*{{{*/
    {
        if (empty($uid))
        {
            AC::$errorNo    =   'UIM004';
            return  FALSE;
        }

        if (!empty(self::$userInfo[$uid]))  
        {
            return  self::$userInfo[$uid];
        }

        $key    =   $this->userInfoKeyPrefix. $uid;
        $result =   Storage::getData($key);

        # if (empty($allInfo))    unset($result['account']);
        if (!empty($result)){
            self::$userInfo[$uid]   =   $result;
        }

        $result['signature'] = UK::getstr($result['signature'],100,'',1);
        $result['nickname']  = UK::getstr($result['nickname'],24,'',1);
        $result['nickname']  = UK::replaceNickname($result['nickname'], $uid); 
        return  $result;
    }/*}}}*/

    public function registerUser($info)/*{{{*/
    {
    	$info['nickname'] = UK::getstr($info['nickname'], 24, '', 1);
    	if (strlen($info['nickname']) < 1)
    	{
    		AC::$errorNo    =   'UIM001';
    		return  FALSE;
    	}
        if (empty($info['uid']) || empty($info['account'])  ||  empty($info['email']) )
        {
            AC::$errorNo    =   'UIM001';
            return  FALSE;
        }

        $data   =   array(
                        'uid'           =>  $info['uid'],
                        'account'       =>  $info['account'],
                        'nickname'      =>  $info['nickname'],
                        'email'         =>  $info['email'],
                        'registerDate'  =>  AC::SERVER_DATE_TIME,
                    );

        $info['sex'] = !in_array($info['sex'],array(0, 1, 2)) ? AC::$sex['secret'] : $info['sex'];
        isset($info['sex'])         &&  $data['sex']        =   $info['sex'];
        isset($info['city'])        &&  $data['city']       =   $info['city'];
        isset($info['type'])        &&  $data['type']       =   $info['type'];
        isset($info['tel'])         &&  $data['tel']        =   $info['tel'];
        isset($info['signature'])   &&  $data['signature']  =   $info['signature'];
        isset($info['birthday'])    &&  $data['birthday']   =   $info['birthday'];
        isset($info['province'])    &&  $data['province']   =   $info['province'];

        $key    =   $this->userInfoKeyPrefix. $info['uid'];
        $result =   Storage::addData($key, $data);
        return  $result;
    }/*}}}*/

    public function setUserInfo($info)/*{{{*/
    {
        if (empty($info['uid']) ||  empty($info['account']))
        {
            AC::$errorNo    =   'UIM002';
            return  FALSE;
        }
       
        /**
         *判断生日
         *传入一组8位的数字，例如20130905
         *只有年月日，不带时分秒的数字。
         *错误代码UIM015年份超出范围
         *UIM016 月份超出范围
         *UIM017 日期超出范围
         */
        if (isset($info['birthday'])) {
            $now     =   date("Y",AC::SERVER_TIME);
            $year    =   substr($info['birthday'], 0,4);
            $moon    =   substr($info['birthday'], 4,2);
            $day     =   substr($info['birthday'], 6,2);
            
            if(strlen($year) < 4 ){
                AC::$errorNo    =   'UIM015';
                return  FALSE;
            }
            
            if(strlen($moon) < 2 ){
                AC::$errorNo    =   'UIM016';
                return  FALSE;
            }
            
            if(strlen($day) < 2  ){
                AC::$errorNo    =   'UIM017';
                return  FALSE;
            }
            
            if ( $now - $year < 0 || $now - $year >100) {
                AC::$errorNo    =   'UIM015';
                return  FALSE;
            } 
            
            if ( $moon < 1 || $moon > 12){
                AC::$errorNo    =   'UIM016';
                return  FALSE;
            }
            
            if ( $day < 1 || $day >31 ){
                AC::$errorNo    =   'UIM017';
                return  FALSE;
            }
        }
        
        /**
         *判断省市
         *传入省份id以及城市id，对应新浪的地理位置表。
         *错误代码UIM018 地理位置不存在
         */
        if (isset($info['province'])) {
          require_once(WEB_SERVER_ROOT_PATH. 'config/Province.php');
          if(empty(Province::$province[$info['province']]) || empty(Province::$city[$info['province']][$info['city']])){
               AC::$errorNo    =   'UIM018';
               return  FALSE;
           }
        }
        isset($info['nickname'])    &&  $data['nickname']   =   UK::getstr($info['nickname'], 24,'',1);
        isset($info['email'])       &&  $data['email']      =   $info['email'];
        isset($info['sex'])         &&  $data['sex']        =   $info['sex'];
        isset($info['city'])        &&  $data['city']       =   intval($info['city']);
        isset($info['province'])    &&  $data['province']   =   intval($info['province']);
        isset($info['type'])        &&  $data['type']       =   $info['type'];
        isset($info['tel'])         &&  $data['tel']        =   $info['tel'];
        isset($info['birthday'])    &&  $data['birthday']   =   intval($info['birthday']);
        isset($info['signature'])   &&  $data['signature']  =   UK::getstr($info['signature'], 100,'',1);
        isset($info['image'])       &&	$data['avatar']     =	UK::getstr($info['image'],255,'',1);
        isset($info['background'])  &&	$data['background'] =	UK::getstr($info['background'],100,'',1);
        isset($info['photos'])      &&	$data['photos']     =	$info['photos'];
        
        if (empty($data))   return  TRUE;

        $key    =   $this->userInfoKeyPrefix. $info['uid'];
        $result =   Storage::setData($key, $data);

        if (FALSE   === $result)    AC::$errorNo    =   'UIM003';
       
        return  $result;
    }/*}}}*/


	public function getVerifiedAbility($id,$length){
		$key    =   $this->abilityKeyPrefix. 0;
		if($id){
			$sql    = "SELECT * FROM xxtuser.ability_0 WHERE `status` = 1 AND `verified` = 1 AND id < {$id} ORDER BY id DESC LIMIT 0,{$length}";
		}else{
			$sql    = "SELECT * FROM xxtuser.ability_0 WHERE `status` = 1 AND `verified` = 1 ORDER BY id DESC LIMIT 0,{$length}";
		}

		$result =   Storage::fetchDbSentenceByClient($key, $sql, 2);
		return $result;
	}
    // 添加达人
    public function addAbility($info){
        if (intval($info['uid']) < 1 || empty($info['content'])){
            AC::$errorNo  = 'UIM024';
            return FALSE;
        }
        if (intval($info['status']) > 2 || intval($info['status']) < 0){
            $info['status'] = '0';
        }
        $data  = array();
        $data['uid']       =    intval($info['uid']);
        $data['content']   =    $info['content'];
        $data['medal_id']  =    '1';
        $data['status']    =    $info['status'];
        $data['label']     =    $info['label'];
        $data['dateline']  =    AC::SERVER_TIME;
        $data['expiration']=    AC::SERVER_TIME + 2678400;
        $data['fans_count']=    $info['followMes_count'];
        
        $key    =   $this->abilityKeyPrefix. 0;
        $result =   Storage::addData($key, $data);
        return  $result;
    }
    
    // 处理达人信息
    public function setAbility($info){
        if (intval($info['uid']) < 1 ){
            AC::$errorNo  = 'UIM024';
            return FALSE;
        }
        $abilityInfo = $this->fetchAbility(array('uid'=>$info['uid']));
        $data = array();
        $data['status'] =    intval($info['status']) > 2 ? '2' : $info['status'];
        isset($info['content']) && $data['content'] = $info['content'];
        isset($info['label'])   && $data['label']   = $info['label'];
        isset($info['followMes_count'])   && $data['fans_count']   = $info['followMes_count'];
        $data['dateline']  =    AC::SERVER_TIME;
        $data['expiration']=    AC::SERVER_TIME + 2678400;
        
        if (empty($data['label'])){
            $data['label']   = $abilityInfo[0]['label'];
        }
        
        $where  =   array('uid'=>$info['uid']);
        $key    =   $this->abilityKeyPrefix. 0;
        $result =   Storage::setConditionData($key, $data, $where);
        return $result;
    }
    
    public function setAbilityLevel($uid, $ability_level) {
        if (intval($uid) < 1 ){
            AC::$errorNo  = 'UIM024';
            return FALSE;
        }
        
        $where  =   array('uid' => $uid);
        $data   =   array('medal_id' => $ability_level);
        $key    =   $this->abilityKeyPrefix. 0;
        $result =   Storage::setConditionData($key, $data, $where);
        return $result;
    }
    
    // 获取达人信息
    public function fetchAbility($info){
        $start  =   0;
        $length =   AC::FEED_LIST_DISPLAY_LEN;
        
        isset($info['start'])  && $start  = intval($info['start']);
        isset($info['length']) && $length = intval($info['length']);
        
        if ($start < 0) $start = 0;
        
        $where = array();
        // 默认显示正式达人
        isset($info['uid'])       &&    $where['uid']       =    $info['uid'];
        isset($info['status'])    &&    $where['status']    =    $info['status'];
        
        empty($info['order']) && $info['order'] = ' DESC ';
        $orderBy =   ' fans_count '.$info['order'];
        $key     =   $this->abilityKeyPrefix. 0;
        $result  =   Storage::getConditionManyData($key, $where, $orderBy, $start, $length);
        
        return  $result;
    }

    public function getAbility($id, $status = 0){
        $id = intval($id);
        $status = intval($status);
        if(empty($id)) return false;
        $where = array();
        // 默认显示正式达人
        $where['id']       =    $id;
        !empty($status)    &&    $where['status']    =    $status;
        $key     =   $this->abilityKeyPrefix. 0;
        $result  =   Storage::getConditionManyData($key, $where);

        return  $result;
    }

    public function getUserRoles($uid)
    {
        if (empty($uid)) return array();

        $where   =   array('uid' => $uid, 'status' => 1);
        $key     =   $this->abilityKeyPrefix. 0 .$this->slaveKey;
        $result  =   Storage::getConditionData($key, $where);

        return  $result;
    }
    
    /*
     * 加入帐号映射表 @param unknown $info @return boolean|Ambigous <unknown, boolean>
     */
    public function addUserConnent ($info)
    {
        if (empty($info['uid']) || empty($info['account'])) {
            AC::$errorNo = 'UIM001';
            return FALSE;
        }
        
        $data = array(
                'uid'           => $info['uid'],
                'open_id'       => $info['account'],
                'open_type'     => $info['open_type'],
                'connent_type'  => $info['connent_type'],
                'open_token'    => $info['open_token'],
                'time'          => AC::SERVER_TIME,
                'status'        => $info['status'],
                'extra'         => $info['extra']
        );
        
        isset($info['open_token']) && $data['open_token'] = $info['open_token'];        
        $key = $this->userConKeyPrefix . $info['uid'];       
        $result = Storage::addData($key, $data);       
        return $result;
    }
    
    /*
     * 获取帐号映射 @param unknown $info @return boolean|Ambigous <unknown, boolean,
     * multitype:>
     */
    public function getUserConnnets ($uid)
    {
        $where = array('uid' => $uid);
        $key = $this->userConKeyPrefix . $uid;        
        $result = Storage::getConditionManyData($key, $where);
        return $result;
    }

    public function getUserConnnetByAccount ($uid, $type)
    {
        $where = array(
                'uid' => $uid,
                'open_type' => $type
        );
        
        $key = $this->userConKeyPrefix . $uid;
    
        $result = Storage::getConditionManyData($key, $where);
        return $result[0];
    }

    public function delUserConnnet ($uid, $type)
	{
        $where = array(
                'uid' => $uid,
                'open_type' => $type
        );
        $key = $this->userConKeyPrefix . $uid; // userconnent
        
        $result = Storage::delConditionData($key, $where);
        return $result;
    }

    public function updateUserConnnet($where, $value, $uid){
        $key = $this->userConKeyPrefix . $uid;
        $result = Storage::setConditionData($key, $value, $where);
        return $result;
    }

    public function updateUserInfo($where ,$value, $uid){
        $key    =   $this->userInfoKeyPrefix. $uid;
        $result =   Storage::setConditionData($key, $value, $where);
        return $result;
    }

    public function getDeviceInfo($model, $codename){
        $key = $this->deviceInfoPrefix. 0;
        $where = 'codename="'.$codename.'" ';
        $where .= 'AND model="'.$model.'" ';
        $where .= 'AND status=0';
        $result = Storage::getConditionManyData($key, $where, 'id asc');
        return $result;
    }

    public function getDeviceAllInfo($model, $codename){
        $key = $this->deviceInfoPrefix. 0;
        $where = 'codename="'.$codename.'" ';
        $where .= 'AND model="'.$model.'" ';
        $result = Storage::getConditionManyData($key, $where, 'id asc');
        return $result;
    }

    public function addDevice($info){
        $new = [
            'status'=>1,//待审核
            'pname' => isset($info['diy']) ? $info['diy'] : $info['model'],
            'brand' => $info['manufacturer'],
            'os' => $info['os'],
            'manufacturer' => $info['manufacturer'],
            'market_name' => isset($info['diy']) ? $info['diy'] : $info['model'],
            'codename' => $info['device'],
            'model' => $info['model']
        ];
        $key = $this->deviceInfoPrefix. 0;
        $result = Storage::addData($key, $new);
        return $result;
    }

    public function getDeviceInfoById($id){
        $key = $this->deviceInfoPrefix. 0;
        $where = 'id="'.$id.'"';
        $result = Storage::getConditionData($key, $where);
        return $result;
    }

    public function getDeviceTextById($id){
        switch ($id){
            case 1:
                return 'Android';
                break;
            case 2:
                return 'iOS';
                break;
            case 3:
                return 'iPad';
                break;
            case 4:
                return 'iPod';
                break;
            default:
                $device = $this->getDeviceInfoById($id);
                if (empty($device)){
                    return '';
                }else{
                    $name = $device['pname'] ? $device['pname'] : $device['market_name'];
                    return trim($name);
                }
                break;
        }
    }
}
